package edu.uclm.esi.tysw.podtube.acciones;

import java.io.File;
import java.util.Random;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import edu.uclm.esi.tysw.podtube.domain.Audio;
import edu.uclm.esi.tysw.podtube.domain.Usuario;

public class SubirAudio extends ActionSupport {
	private static final long serialVersionUID = 1L;

	private File upload; 				// The actual file
	private String uploadContentType; 	// The content type of the file
	private String uploadFileName; 		// The uploaded file name
	private String fileCaption; 		// The caption of the file entered by user
	private String tempFileName;
	private String palabraClave1;
	private String palabraClave2;
	private String palabraClave3;

	public String execute() throws Exception {
		try {
			String tmpFolder = System.getProperty("java.io.tmpdir");
			int rnd = Math.abs(new Random().nextInt());
			this.tempFileName = tmpFolder + "/" + rnd;
			File theFile = new File(tempFileName);
			FileUtils.copyFile(upload, theFile);

			Usuario user = (Usuario) ActionContext.getContext().getSession().get("user");

			Audio audio = new Audio(this.tempFileName, this.uploadFileName, this.palabraClave1, this.palabraClave2, this.palabraClave3);
			audio.setUsuario(user);

			audio.insert();
			return SUCCESS;
		} catch (Exception e) {
			addActionError(e.getMessage());
			return INPUT;
		}
	}

	public String getFileCaption() {
		return fileCaption;
	}

	public void setFileCaption(String fileCaption) {
		this.fileCaption = fileCaption;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getTempFileName() {
		return tempFileName;
	}

	public void setTempFileName(String tempFileName) {
		this.tempFileName = tempFileName;
	}

	public void setPalabraClave1(String palabraClave) {
		if (palabraClave == null || palabraClave.trim().length() == 0) {
			this.palabraClave1 = null;
			return;
		}
		this.palabraClave1 = palabraClave;
	}

	public void setPalabraClave2(String palabraClave) {
		if (palabraClave == null || palabraClave.trim().length() == 0) {
			this.palabraClave2 = null;
			return;
		}
		this.palabraClave2 = palabraClave;
	}

	public void setPalabraClave3(String palabraClave) {
		if (palabraClave == null || palabraClave.trim().length() == 0) {
			this.palabraClave3 = null;
			return;
		}
		this.palabraClave3 = palabraClave;
	}

}
